package cn.wolfcode.crm.realm;

import cn.wolfcode.crm.domain.Employee;
import cn.wolfcode.crm.mapper.EmployeeMapper;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;

public class myRealm extends AuthorizingRealm {

    @Autowired
    private EmployeeMapper employeeMapper;


    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("--------------------------");
        Employee employee = (Employee) principalCollection.getPrimaryPrincipal();
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        if (employee.isAdmin()) {
            info.addStringPermission("*:*");
            info.addRole("admin");
        } else {
            List<String> permissions = employeeMapper.selectPermissionExpressionByEmplId(employee.getId());
            info.addStringPermissions(permissions);

            //查询用户角色集合
            List<String> roleSns = employeeMapper.selectEmploRoleSnsByEmploId(employee.getId());
            info.addStringPermissions(roleSns);
        }
        return info;
    }

    /**
     * @param authenticationToken
     * @return
     * @throws AuthenticationException
     */
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        String principal = (String) authenticationToken.getPrincipal();
        Employee employee = employeeMapper.selectEmplByUsername(principal);
        if (employee != null) {
            return new SimpleAuthenticationInfo(employee, employee.getPassword(),
                    ByteSource.Util.bytes(employee.getName()), getName());
        }
        return null;
    }
}
